package org.dromara.system.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.oss.core.OssClient;
import org.dromara.common.oss.factory.OssFactory;
import org.dromara.system.domain.SysSolutionDocEn;
import org.dromara.system.domain.bo.SysSolutionDocEnBo;
import org.dromara.system.domain.vo.SysSolutionDocEnVo;
import org.dromara.system.mapper.SysSolutionDocEnMapper;
import org.dromara.system.service.ISysSolutionDocEnService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.List;

/**
 * English Solution Document Service Implementation
 *
 * @author system
 */
@RequiredArgsConstructor
@Service
public class SysSolutionDocEnServiceImpl implements ISysSolutionDocEnService {

    private final SysSolutionDocEnMapper baseMapper;

    /**
     * Query solution document list
     *
     * @param queryBo   Query parameters
     * @param pageQuery Pagination parameters
     * @return Solution document paginated list
     */
    @Override
    public TableDataInfo<SysSolutionDocEnVo> queryPageList(SysSolutionDocEnBo queryBo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysSolutionDocEn> lqw = buildQueryWrapper(queryBo);
        Page<SysSolutionDocEnVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    private LambdaQueryWrapper<SysSolutionDocEn> buildQueryWrapper(SysSolutionDocEnBo queryBo) {
        LambdaQueryWrapper<SysSolutionDocEn> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(queryBo.getDocName()), SysSolutionDocEn::getDocName, queryBo.getDocName());
        // Query by name fuzzy search only
        lqw.orderByDesc(SysSolutionDocEn::getCreateTime);
        return lqw;
    }

    /**
     * Query solution document detail
     *
     * @param docId Document ID
     * @return Solution document detail
     */
    @Override
    public SysSolutionDocEnVo queryById(Long docId) {
        SysSolutionDocEn entity = baseMapper.selectById(docId);
        return MapstructUtils.convert(entity, SysSolutionDocEnVo.class);
    }


    /**
     * Upload PDF folder solution
     * ⭐ KEY CHANGE: MinIO path changed to pdf-solutions-en/
     */
    @Override
    public SysSolutionDocEnVo uploadPdfFolderSolution(MultipartFile[] files, String folderName, String remark) {
        if (files == null || files.length == 0) {
            throw new ServiceException("Folder cannot be empty");
        }

        // Identify main PDF file (base file name ends with -main, extension is .pdf)
        String mainFileName = null;

        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            if (StringUtils.isNotBlank(fileName)) {
                String lower = fileName.toLowerCase();
                int dotIdx = lower.lastIndexOf('.');
                String baseName = dotIdx > 0 ? lower.substring(0, dotIdx) : lower;
                boolean isPdf = lower.endsWith(".pdf");
                boolean baseEndsWithMain = baseName.endsWith("-main");
                if (isPdf && baseEndsWithMain) { mainFileName = fileName; break; }
            }
        }

        if (StringUtils.isBlank(mainFileName)) {
            throw new ServiceException("Main PDF file not found (base file name ends with -main, extension is .pdf)");
        }

        try {
            // Fallback solution name: if folderName not provided, use main file name without .pdf and trailing -main as solution name
            String resolvedFolderName = folderName;
            if (StringUtils.isBlank(resolvedFolderName)) {
                String mf = mainFileName;
                int dot = mf.lastIndexOf('.');
                String base = dot > 0 ? mf.substring(0, dot) : mf;
                if (base.endsWith("-main")) {
                    base = base.substring(0, base.length() - 5);
                }
                resolvedFolderName = StringUtils.isNotBlank(base) ? base : "solution";
            }

            // ⭐ KEY CHANGE: Generate unique folder path with English prefix
            String uniqueFolderPath = "pdf-solutions-en/" + resolvedFolderName + "-" + IdUtil.simpleUUID() + "/";

            OssClient ossClient = OssFactory.instance();
            String mainFileUrl = null;
            int totalFileCount = 0;

            for (MultipartFile file : files) {
                String originalFileName = file.getOriginalFilename();
                if (StringUtils.isBlank(originalFileName)) {
                    continue;
                }

                String fileKey = uniqueFolderPath + originalFileName;
                ossClient.upload(file.getInputStream(), fileKey, file.getSize(), file.getContentType());
                totalFileCount++;

                if (mainFileName.equals(originalFileName)) {
                    mainFileUrl = ossClient.getUrl() + "/" + fileKey;
                }
            }

            if (StringUtils.isBlank(mainFileUrl)) {
                throw new ServiceException("Main file upload failed");
            }

            SysSolutionDocEn solutionDoc = new SysSolutionDocEn();
            solutionDoc.setDocName(resolvedFolderName);
            solutionDoc.setDocUrl(mainFileUrl);
            solutionDoc.setMainFileName(mainFileName);
            // PDF solution does not need resource folder
            // No resource folder
            solutionDoc.setFolderPath(uniqueFolderPath);
            solutionDoc.setTotalFiles(totalFileCount);
            solutionDoc.setRemark(remark);

            baseMapper.insert(solutionDoc);

            return MapstructUtils.convert(solutionDoc, SysSolutionDocEnVo.class);

        } catch (Exception e) {
            throw new ServiceException("PDF folder upload failed: " + e.getMessage());
        }
    }

    /**
     * Update solution document
     *
     * @param bo Solution document
     * @return Result
     */
    @Override
    public Boolean updateByBo(SysSolutionDocEnBo bo) {
        SysSolutionDocEn update = new SysSolutionDocEn();
        update.setDocId(bo.getDocId());
        update.setDocName(bo.getDocName());
        update.setDocUrl(bo.getDocUrl());
        update.setMainFileName(bo.getMainFileName());
        update.setFolderPath(bo.getFolderPath());
        update.setTotalFiles(bo.getTotalFiles());
        update.setRemark(bo.getRemark());
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * Data validation before save
     */
    private void validEntityBeforeSave(SysSolutionDocEn entity) {
        // TODO Data validation, such as unique constraints
    }

    /**
     * Batch delete solution documents
     *
     * @param ids Solution document IDs to delete
     * @return Result
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO Business validation, determine if validation is needed
        }
        List<SysSolutionDocEn> list = baseMapper.selectByIds(ids);
        for (SysSolutionDocEn solutionDoc : list) {
            // Delete solution folder
            if (StringUtils.isNotBlank(solutionDoc.getFolderPath())) {
                try {
                    OssClient ossClient = OssFactory.instance();
                    // Delete entire folder (need to list all files in folder then delete one by one)
                    // Note: Simplified handling here, may need adjustment based on specific OSS implementation
                    ossClient.delete(solutionDoc.getFolderPath());
                } catch (Exception e) {
                    // Log but do not block deletion operation
                    // log.warn("Delete OSS folder failed: {}", solutionDoc.getFolderPath(), e);
                }
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * Preview or download solution document
     *
     * @param docId       Document ID
     * @param disposition Display mode: inline-preview, attachment-download
     * @param response    Response object
     */
    @Override
    public void previewDocument(Long docId, String disposition, HttpServletResponse response) throws Exception {
        SysSolutionDocEn solutionDoc = baseMapper.selectById(docId);
        if (solutionDoc == null) {
            throw new ServiceException("Document does not exist");
        }

        // ⭐ KEY CHANGE: Use English user-side anonymous file route for preview with usable relative links
        String mainName = solutionDoc.getMainFileName();
        String target = "/user/pdf-solution-en/file/" + docId + "/" + java.net.URLEncoder.encode(mainName, java.nio.charset.StandardCharsets.UTF_8.name()).replace("+", "%20");
        response.sendRedirect(target);
    }
}

